<template>
  <Container class="brand-list">
    <Tabs v-model="tab">
      <TabPane label="云豆设置" name="tab1" class="scroll">
        <div class="bg-light mt pb">
          <div class="container-title">云豆设置</div>
          <Form ref="form" :model="dateAndOrderForm" :rules="rules" :label-width="20">
            <FormItem prop="storeTypeList">
              <CheckboxGroup v-model="dateAndOrderForm.storeTypeList">
                <span class="font-red">*</span>
                <Checkbox v-for="item in storeTypeData" :key="item.id" :label="item.value" class="mr">{{item.text}}</Checkbox>
              </CheckboxGroup>
            </FormItem>
            <FormItem prop="date">
              <Row>
                <i-col>
                  有效时间
                  <DatePicker
                    v-model="dateAndOrderForm.date"
                    style="width: 200px"
                    format="yyyy-MM-dd"
                    type="daterange"
                    placement="bottom-start"
                    placeholder="有效时间"
                    class="ml"/>
                </i-col>
              </Row>
            </FormItem>
            <FormItem>
              <Row>
                <i-col>每个工厂抢购订单(需订单内全部工厂抢购商品)大于等于
                  <InputNumber v-model="dateAndOrderForm.productNum" :max="999999" :min="1" class="ml mr" />条，送
                  <InputNumber v-model="dateAndOrderForm.goldNum" :max="999999" :min="1" class="ml mr"/>云豆
                  <Button class="ml" type="primary" :disabled="!saveRight || disabled" @click="onSave">保存</Button>
                </i-col>
              </Row>
            </FormItem>
          </Form>
        </div>
        <div class="bg-light">
          <div class="container-title">扫描入库送云豆</div>
          <div class="pl pr">
              <Row 
                class="mb pl pr mbc" 
                type="flex" 
                justify="space-around" 
                align="middle" 
                v-for="(item, index) in tireGoldRuleList" :key="index">
                <i-col span="16">
                  <span class="font-blue">{{ item.tireSize }}</span>寸扫码正常入库{{ item.isMatch ? '并且匹配了特价订单，并且特价订单商品总数量大于等于' + item.productNum : '且入库匹配特价订单' }},送{{ item.goldNum }}云豆
                </i-col>
                <i-col span="8" class="tr">
                  <Button type="primary" :disabled="!sendSpecAndSizeRight" @click="onAddEdit(item, index)">经销商额外送豆</Button>
                  <Button type="success" :disabled="!editSpecAndSizeRight" @click="onSizeEdit(item, index)">编辑</Button>
                  <Button type="warning" :disabled="!deleteSpecAndSizeRight" @click="onSizeRemove(item, index)">删除</Button>
                </i-col>
              </Row>
              <div class="bt-center pb">
                <Button 
                    type="dashed"
                    size="large"
                    icon="md-add"
                    :disabled="!addSpecAndSizeRight" 
                    @click="onAddSize"
                    class="mb">添加一个尺寸</Button>
              </div>
          </div>
        </div>
        <div class="bg-light">
          <div class="container-title">
            <span>扫码入库送云豆(按具体商品送)</span>
            <div slot="extra" class="flexL">
              <Input
                v-model.trim="productTitle"
                class="start"
                placeholder="商品名称"
                @on-enter="onSearchBtnClick"
                @on-search="onSearchBtnClick"
                search 
                enter-button/>
            </div>
          </div>
          <div class="pl pr">
              <Row
                class="mb pl pr mbc" 
                type="flex" 
                justify="space-around" 
                align="middle"  v-for="(item, index) in productGoldRuleDTOList" :key="index">
                <i-col span="16">
                  <span class="font-blue">{{ item.productTitle }}</span>扫码正常入库{{ item.isMatch ? '并且匹配了特价订单，并且特价订单商品总数量大于等于' + item.productNum : '且入库匹配特价订单' }},送{{ item.goldNum }}云豆
                </i-col>
                <i-col span="8" class="tr">
                  <Button type="primary" :disabled="!sendSpecAndSizeRight" @click="onAddEdit(item, index)">经销商额外送豆</Button>
                  <Button type="success" :disabled="!editSpecAndSizeRight" @click="onGoodsEdit(item, index)">编辑</Button>
                  <Button type="warning" :disabled="!deleteSpecAndSizeRight" @click="onGoodsRemove(item, index)">删除</Button>
                </i-col>
              </Row>
              <div class="pager" v-if="productGoldRuleDTOList.length">
                <Page
                  :total="totalItem"
                  :current="currentPage"
                  :page-size="pageSize"
                  show-sizer
                  placement="top"
                  @on-change="onPageChange"
                  @on-page-size-change="onPageSizeChange"
                />
              </div>
              <div class="tc mb" v-else>暂无数据</div>
              <div class="bt-center pb">
                <Button 
                    type="dashed"
                    size="large"
                    icon="md-add"
                    :disabled="!addSpecAndSizeRight"
                    @click="onAddGoods"
                    class="mb">添加一个规格</Button>
              </div>
          </div>
        </div>
        <div class="bg-light pb">
          <div class="container-title">
              <span>任务完成送云豆</span>
              <div slot="extra" class="font-red normal">注意：如门店同时满足多个规则，会送多次。</div>
          </div>
          <div class="pl pr">
            <Row 
              class="mb pl pr borderB mbc" 
              type="flex" 
              justify="center"
              align="middle"
              v-for="(item, index) in storeGoldRuleGroupList" :key="index">
              <i-col span="16">
                <div v-for="(i, j) in item.storeGoldRuleDTOMap" :key="j" class="mb">
                  <span class="db font-blue">{{toChangeType(i.storeTypeEnum)}}</span>任务完成率大于等于{{i.minPercentage}}%，小于{{i.maxPercentage}}%，送{{i.goldNum}}云豆
                </div>
              </i-col>
              <i-col span="8" class="tr">
                <Button type="success" :disabled="!editRuleRight" @click="onTaskEdit(item, index)">编辑</Button>
                <Button type="warning" :disabled="!deleteRuleRight" @click="onTaskRemove(item, index)">删除</Button>
              </i-col>
            </Row>
            <div class="bt-center pb">
              <Button 
                  type="dashed"
                  size="large"
                  icon="md-add"
                  :disabled="!addRuleRight"
                  @click="onTask"
                  class="mb">添加一个规则</Button>
            </div>
          </div>
        </div>
      </TabPane>
    </Tabs>
    <ScanItem ref="scanEdit" @scan="getSizeList" />
    <GoodsItem ref="goodsEdit" @goods="getGoodsList" />
    <DistributorItem ref="distributorEdit" @distributor="getData" />
    <!-- <TaskItem ref="taskEdit" @task="getData" :size="size" :storeTypeList="dateAndOrderForm.storeTypeList"></TaskItem> -->
    <TaskItem ref="taskEdit" :size="size" @task="getData" />
  </Container>
</template>
<script>
import ScanItem from './edit/ScanItem'
import TaskItem from './edit/TaskItem'
import GoodsItem from './edit/GoodsItem'
import DistributorItem from './edit/DistributorItem'
import { formatDate } from '@/util'
import { mapGetters } from 'vuex'
export default {
  components: {
    ScanItem,
    TaskItem,
    GoodsItem,
    DistributorItem
  },
  data () {
    return {
      dateAndOrderForm: {
        goldNum: null,
        productNum: null,
        date: null,
        storeTypeList: []
      },
      rules: {
        storeTypeList: [{ required: true, message: '请选择门店类型', type: "array", trigger: 'blur' }],
        date: [{
            required: true,
            message: "请选择开始时间",
            trigger: "blur",
            type: "array",
            fields: {
              0: { type: "date", required: true, message: "请选择有效开始日期" },
              1: { type: "date", required: true, message: "请选择有效结束日期" }
            }
          }
        ]
      },
      productTitle: '',
      newArr: null,
      index: 1,
      tireGoldRuleList: [],
      productGoldRuleDTOList: [],
      storeGoldRuleGroupList: [],
      tab: 'tab1',
      disabled: false,
      size: 1,
      totalItem: 1,
      pageSize: window.$pageSize,
      currentPage: 1,
      saveRight: true, //保存权限
      addSpecAndSizeRight: true, //添加尺寸,规格权限
      editSpecAndSizeRight: true, //编辑尺寸,规格权限
      deleteSpecAndSizeRight: true, //删除尺寸,规格权限
      sendSpecAndSizeRight: true, //额外送豆权限
      addRuleRight: true, //添加规则权限
      editRuleRight: true, //编辑规则权限
      deleteRuleRight: true, //删除规则权限
      viewUrls: [
        { key: 'saveRight', url: '/sales/gold/rule/saveDateAndOrder' },
        { key: 'addSpecAndSizeRight', url: '/sales/gold/rule/saveProduct' },
        { key: 'editSpecAndSizeRight', url: '/sales/gold/rule/editProduct' },
        { key: 'deleteSpecAndSizeRight', url: '/sales/gold/rule/delProduct' },
        { key: 'sendSpecAndSizeRight', url: '/sales/gold/rule/exceptionalInfo' },
        { key: 'addRuleRight', url: '/sales/gold/rule/saveStore' },
        { key: 'editRuleRight', url: '/sales/gold/rule/editStore' },
        { key: 'deleteRuleRight', url: '/sales/gold/rule/delStore' }
      ]
    }
  },
  computed: {
    storeTypeData () {
      return this.$store.getters.storeTypeData
    },
    ...mapGetters(['userMenu']),
    toChangeType: function () {
      return function (v) {
        let obj = {}
        this.storeTypeData.map((item, index) => {
          obj[item.value] = item.text
        })
        return obj[v]
      }
    }
  },
  created () {
    this.getSizeList()
    this.getGoodsList()
    this.userMenu.forEach(item => {
      this.viewUrls.forEach(child => {
        if (item.viewUrl === child.url) {
          this[child.key] = item.hasRight
        }
      })
    })
  },
  mounted () {
    this.getData()
    this.$store.dispatch('getStoreType')
    this.getTest()
  },
  methods: {
    getTest () {
      let obj = {}
      this.storeTypeData.map((item, index) => {
        obj[item.value] = item.text
      })
      this.newArr = obj
    },
    getSizeList () {
      this.$ajaxGet('/gold/rule/list_tire_size').then(data => {
        if (data) {
          this.tireGoldRuleList = data
        }
        this.backTableTop()
      }).catch(() => {
      })
    },
    onSearchBtnClick () {
      this.currentPage = 1
      this.getGoodsList()
    },
    getGoodsList () {
      let param = {
        current: this.currentPage,
        size: this.pageSize,
        productTitle: this.productTitle
      }
      this.$ajaxGet('/gold/rule/list_product', param).then(data => {
        if (data.records) {
          this.productGoldRuleDTOList = data.records
          this.totalItem = Number(data.total)
        }
        this.backTableTop()
      }).catch(() => {
      })
    },
    onPageChange (number) {
      this.currentPage = number
      this.$router.push({
        name: 'sales/gold/edit',
        query: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      })
      this.getGoodsList()
    },
    onPageSizeChange (pageSize) {
      this.currentPage = 1
      this.pageSize = pageSize
      this.$router.push({
        name: 'sales/gold/edit',
        query: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      })
      this.getGoodsList()
    },
    getData () {
      this.$ajaxGet('/gold/rule').then(data => {
        this.dateAndOrderForm = {
          goldNum: data.orderGoldRule ? data.orderGoldRule.goldNum : null,
          productNum: data.orderGoldRule ? data.orderGoldRule.productNum : null,
          date: [data.ruleStartDate, data.ruleEndDate],
          storeTypeList: data.storeTypeList
        }
        if (this.storeGoldRuleGroupList) {
          this.storeGoldRuleGroupList = data.storeGoldRuleGroupList
          let maxNum = data.storeGoldRuleGroupList.map(item => {
            return item.group
          })
          this.size = data.storeGoldRuleGroupList.length > 0 ? Math.max.apply(null, maxNum) : 0
        }
        this.backTableTop()
      }).catch(() => {
      })
    },
    onAddEdit (item) {
      this.$refs.distributorEdit.openForm(item)
    },
    onAddGoods () {
      this.$refs.goodsEdit.openForm()
    },
    onGoodsEdit (item) {
      this.$refs.goodsEdit.openForm(item)
    },
    onAddSize () {
      this.$refs.scanEdit.openForm()
    },
    onSizeEdit (item) {
      this.$refs.scanEdit.openForm(item)
    },
    onSizeRemove (item, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除当前尺寸？',
        onOk: () => {
          this.$jsonPost('/gold/rule/del_product/' + item.id).then(data => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.tireGoldRuleList.splice(index, 1)
          })
        }
      })
    },
    onGoodsRemove (item, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除当前商品？',
        onOk: () => {
          this.$jsonPost('/gold/rule/del_product/' + item.id).then(data => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.productGoldRuleDTOList.splice(index, 1)
          })
        }
      })
    },
    onTask () {
      this.$refs.taskEdit.openForm()
    },
    onTaskEdit (item) {
      this.$refs.taskEdit.openForm(item)
    },
    onTaskRemove (item, index) {
      this.$Modal.confirm({
        title: '删除',
        content: '确定删除当前尺寸？',
        onOk: () => {
          let param = {
            group: item.group,
            storeGoldRuleDTOMap: item.storeGoldRuleDTOMap
          }
          this.$jsonPost('/gold/rule/del_store', param).then(data => {
            this.$Notice.success({
              title: '删除成功'
            })
            this.storeGoldRuleGroupList.splice(index, 1)
          })
        }
      })
    },
    onSave () {
      if (this.disabled) return
      this.$refs["form"].validate(valid => {
        if (valid) {
          let url = '/gold/rule/save_dateAndOrder'
          let param = {
            ruleStartDate: formatDate(this.dateAndOrderForm.date[0]) + ' 00:00:00',
            ruleEndDate: formatDate(this.dateAndOrderForm.date[1]) + ' 23:59:59',
            storeTypeList: this.dateAndOrderForm.storeTypeList
          }
          if (this.dateAndOrderForm.goldNum && this.dateAndOrderForm.productNum == null) {
            this.$Notice.warning({
              title: '条数不能为空'
            })
            return
          }
          if (this.dateAndOrderForm.productNum && this.dateAndOrderForm.goldNum == null) {
            this.$Notice.warning({
              title: '云豆不能为空'
            })
            return
          }
          if (this.dateAndOrderForm.goldNum || this.dateAndOrderForm.productNum) {
            param.orderGoldRule = {
              goldNum: this.dateAndOrderForm.goldNum,
              productNum: this.dateAndOrderForm.productNum
            }
          }
          this.$jsonPost(url, param).then(data => {
            this.$Notice.success({
              title: '保存成功'
            })
            this.disabled = false
          }).catch(() => {
            this.disabled = false
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.bt-center{
  margin: 0 auto;
  text-align: center
}
.mbc {
  padding-bottom: 10px;
  border-bottom: 1px #D1D1D1 dashed;
}
</style>